import axios from "axios";
import { getJumpTarget, initServerJumpTargetConfig } from "./setting";

axios.interceptors.request.use(
    (config) => {
        // 从localStorage获取token并添加到请求头
        const token = window.localStorage.getItem("_token");
        if (token) {
            config.headers.Authorization = token;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);
axios.interceptors.response.use(
    (response) => response,
    (error) => {
        if (error.response?.status === 401) {
            // Clear token and redirect to login
            window.localStorage.removeItem("_token");
            window.location.href = "/login";
        }
        return Promise.reject(error);
    }
);
const baseUrl = "/api/";
// const baseUrl = "https://tools.mereith.com/api/";

const selfJumpIcon = ``
const blankJumpIcon = ``
export const FetchList = async () => {
    const { data: raw } = await axios.get(baseUrl);
    const { data } = raw;
    // 获取分类
    const catelogs = [];
    catelogs.push("全部工具")
    data.catelogs.forEach(item => {
        catelogs.push(item.name)
    })
    if (!data.tools) {
        data.tools = []
    }
    data.tools.forEach(item => {
        if (!catelogs.includes(item.catelog)) {
            catelogs.push(item.catelog);
        }
    });
    if (!data.setting?.hideAdmin) {
        data.tools.push({
            id: 999999999999,
            catelog: "管理后台",
            name: "本站管理后台",
            desc: "本导航站的管理后台哦",
            url: "admin",
            logo: ``,
        })
    }
    if (data.setting) {
        initServerJumpTargetConfig(data.setting)
    }

    const jumpTarget = getJumpTarget();

    data.tools.push({
        id: 999099999978,
        catelogs: "偏好设置",
        name: jumpTarget === "blank" ? "新建窗口" : "原地跳转",
        desc: `点击切换跳转方式`,
        url: "toggleJumpTarget",
        logo: jumpTarget === "blank" ? blankJumpIcon : selfJumpIcon
    })

    data.catelogs = catelogs;
    return data;
};




export const login = async (username: string, password: string) => {
    const { data } = await axios.post("/api/login", {
        name: username,
        password,
    });
    return data;
};

export const fetchAdminData: () => Promise<any> = async () => {
    const { data } = await axios.get("/api/admin/all");
    return data?.data || {};
};
export const fetchImportTools = async (payload: any) => {
    const { data } = await axios.post(`/api/admin/importTools`, payload);
    return data?.data || {};
};
export const fetchExportTools = async () => {
    const { data } = await axios.get(`/api/admin/exportTools`);
    return data?.data;
};
// 工具管理接口：删除、修改、新增
export const fetchDeleteTool = async (id: number) => {
    const { data } = await axios.delete(`/api/admin/tool/${id}`);
    return data?.data || {};
};
export const fetchUpdateTool = async (payload: any) => {
    const { data } = await axios.put(`/api/admin/tool/${payload.id}`, payload);
    return data?.data || {};
};
export const fetchAddTool = async (payload: any) => {
    const { data } = await axios.post(`/api/admin/tool`, payload);
    return data?.data || {};
};
// 分类管理接口；新增、修改、删除
export const fetchAddCateLog = async (payload: any) => {
    const { data } = await axios.post(`/api/admin/catelog`, payload);
    return data?.data || {};
};
export const fetchUpdateCateLog = async (payload: any) => {
    const { data } = await axios.put(`/api/admin/catelog/${payload.id}`, payload);
    return data?.data || {};
};
export const fetchDeleteCatelog = async (id: number) => {
    const { data } = await axios.delete(`/api/admin/catelog/${id}`);
    return data?.data || {};
};

export const fetchUpdateSetting = async (payload: any) => {
    const { data } = await axios.put(`/api/admin/setting`, payload);
    return data?.data || {};
};

export const fetchUpdateUser = async (payload: any) => {
    const { data } = await axios.put(`/api/admin/user`, payload);
    return data?.data || {};
};

export const fetchAddApiToken = async (payload: any) => {
    const { data } = await axios.post(`/api/admin/apiToken`, payload);
    return data?.data || {};
};
export const fetchDeleteApiToken = async (id: number) => {
    const { data } = await axios.delete(`/api/admin/apiToken/${id}`);
    return data?.data || {};
};
export const fetchUpdateToolsSort = async (updates: { id: number; sort: number }[]) => {
    const { data } = await axios.put(`/api/admin/tools/sort`, updates);
    return data?.data || {};
};